package com.server.push;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.push20160801.AsyncClient;
import com.aliyun.sdk.service.push20160801.models.PushRequest;
import com.aliyun.sdk.service.push20160801.models.PushResponse;
import com.google.gson.Gson;
import com.server.pojo.Alarm;
import com.server.pojo.MobileApp;
import com.server.pojo.Notice;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * Created by lingbo on 16/8/15.
 */
@Slf4j
public class AliYunPush {
    protected static String region = "cn-beijing";
    protected static long iosAppKey = 335249247;
    protected static long androidAppKey = 334934419;
    protected static String accessKeyId = "LTAI5tJnyccoZo6mHDhjHDaU";
    protected static String  accessKeySecret = "zpBVgy6HoM0NEK0pjjMkeLjXrcfp1y";

    static AsyncClient createClient(){
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        return AsyncClient.builder()
                .region("cn-qingdao") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("cloudpush.aliyuncs.com")
                )
                .build();
    }

    /**
     * 推送通知给iOS
     * <p>
     * 参见文档 https://help.aliyun.com/document_detail/48088.html
     */


    /**
     * 推送高级接口
     * <p>
     * 参见文档 https://help.aliyun.com/document_detail/48089.html
     * //
     */
    public static void alarm(List<MobileApp> mobileApps, Alarm alarm) {

        // 分组：iOS 和 Android
        List<String> iosDeviceIds = new ArrayList<>();
        List<String> androidDeviceIds = new ArrayList<>();
        for (MobileApp mobileApp : mobileApps) {
            String deviceId = mobileApp.getDeviceId();
            if (deviceId != null && !deviceId.isEmpty()) {
                if ("ios".equalsIgnoreCase(mobileApp.getDeviceType())) {
                    iosDeviceIds.add(deviceId);
                } else if ("android".equalsIgnoreCase(mobileApp.getDeviceType())) {
                    androidDeviceIds.add(deviceId);
                }
            }
        }

        if(!iosDeviceIds.isEmpty()){
            try {
                AsyncClient client = createClient();
                PushRequest pushRequest = PushRequest.builder()
                        .appKey(iosAppKey)
                        .pushType("NOTICE")
                        .deviceType("iOS")
                        .target("DEVICE")
                        .targetValue(String.join(",", iosDeviceIds))
                        .title("联动消息")
                        .body(alarm.getUnit().getName())
                        .iOSMusic("JB.wav")

                        .build();


                CompletableFuture<PushResponse> response = client.push(pushRequest);
                PushResponse resp = response.get();
                System.out.println(new Gson().toJson(resp));
                client.close();
            } catch (Exception e) {
                log.error("iOS推送失败，设备ID: {}, 错误信息: {}", iosDeviceIds, e.getMessage(), e);

            }

        }
        if(!androidDeviceIds.isEmpty()){
            try {
                AsyncClient client = createClient();
                PushRequest pushRequest = PushRequest.builder()
                        .appKey(androidAppKey)
                        .pushType("NOTICE")
                        .deviceType("ANDROID")
                        .target("DEVICE")
                        .targetValue(String.join(",", androidDeviceIds))
                        .title("联动消息")
                        .body(alarm.getUnit().getName())
                        .build();


                CompletableFuture<PushResponse> response = client.push(pushRequest);
                PushResponse resp = response.get();
                System.out.println(new Gson().toJson(resp));
                client.close();
            } catch (Exception e) {
                log.error("ANDROID推送失败，设备ID: {}, 错误信息: {}", androidDeviceIds, e.getMessage(), e);

            }

        }

    }


    public static void notice(List<MobileApp> mobileApps, Notice notice) {

        // 分组：iOS 和 Android
        List<String> iosDeviceIds = new ArrayList<>();
        List<String> androidDeviceIds = new ArrayList<>();
        for (MobileApp mobileApp : mobileApps) {
            String deviceId = mobileApp.getDeviceId();
            if (deviceId != null && !deviceId.isEmpty()) {
                if ("ios".equalsIgnoreCase(mobileApp.getDeviceType())) {
                    iosDeviceIds.add(deviceId);
                } else if ("android".equalsIgnoreCase(mobileApp.getDeviceType())) {
                    androidDeviceIds.add(deviceId);
                }
            }
        }

        if(!iosDeviceIds.isEmpty()){
            try {
                AsyncClient client = createClient();
                PushRequest pushRequest = PushRequest.builder()
                        .appKey(iosAppKey)
                        .pushType("NOTICE")
                        .deviceType("iOS")
                        .target("DEVICE")
                        .targetValue(String.join(",", iosDeviceIds))
                        .title(notice.getTitle())
                        .body(notice.getBody())
                        .build();


                CompletableFuture<PushResponse> response = client.push(pushRequest);
                PushResponse resp = response.get();
                System.out.println(new Gson().toJson(resp));
                client.close();
            } catch (Exception e) {
                log.error("iOS推送失败，设备ID: {}, 错误信息: {}", iosDeviceIds, e.getMessage(), e);

            }

        }
        if(!androidDeviceIds.isEmpty()){
            try {
                AsyncClient client = createClient();
                PushRequest pushRequest = PushRequest.builder()
                        .appKey(androidAppKey)
                        .pushType("NOTICE")
                        .deviceType("ANDROID")
                        .target("DEVICE")
                        .targetValue(String.join(",", androidDeviceIds))
                        .title(notice.getTitle())
                        .body(notice.getBody())
                        .build();


                CompletableFuture<PushResponse> response = client.push(pushRequest);
                PushResponse resp = response.get();
                System.out.println(new Gson().toJson(resp));
                client.close();
            } catch (Exception e) {
                log.error("ANDROID推送失败，设备ID: {}, 错误信息: {}", androidDeviceIds, e.getMessage(), e);

            }

        }

    }
}
